import React, { Component } from 'react';
import { List, Modal, Toast, WingBlank } from 'antd-mobile';
import { AsyncStorage, Button, Image, ScrollView, StatusBar, Text, TouchableWithoutFeedback, View } from 'react-native';
import styles from './style';
const Item = List.Item;
const alert = Modal.alert;

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
    this.getData = this.getData.bind(this);
    this.renderPureText = this.renderPureText.bind(this);
    this.renderOnePicText = this.renderOnePicText.bind(this);
    this.renderThreePicText = this.renderThreePicText.bind(this);
  }

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    return {
      title: '我的收藏',
      headerTitleStyle: {
        color: '#fff',
      },
      headerStyle: {
        backgroundColor: '#ed4040'
      },
      headerLeft: (
        <TouchableWithoutFeedback onPress={() => {
          Toast.hide();
          navigation.goBack();
        }}>
          <View>
            <Image style={{ width: 23, height: 23, tintColor: '#fff', marginLeft: 10 }}
                   source={require('../../images/back.png')}
                   resizeMode="cover"
            />
          </View>
        </TouchableWithoutFeedback>
      ),
      headerRight: (
        <Button title="清除" color="#fff" onPress={() => params.clickRight()}>
        </Button>
      ),
      tabBarIcon: ({ tintColor }) => (
        <Image
          source={require('../../images/search.png')}
          style={[styles.icon, { tintColor: tintColor }]}
        />
      ),
    }
  };

  componentDidMount() {
    const navigation = this.props.navigation;
    this.props.navigation.setParams({
      clickLeft: navigation.goBack,
      clickRight: this.showActionSheet.bind(this)
    });
    AsyncStorage.getItem('collection', (err, result) => {
      if (err || !result) {
        return false;
      }
      let ids = [];
      try {
        ids = JSON.parse(result);
      } catch (ex) {
        console.log(ex);
      }
      this.getData(ids);
    })
  }

  async getData(ids) {
    Toast.loading('加载中...', 999999999999);
    let f = await fetch(`https://ecmad.com/toutiao/api/article/collection?ids=${ids.join(',')}`, {
      method: 'GET',
    }).catch(() => {
      Toast.offline('网络异常', 2, f => f, false);
    });
    let res = await f.json();
    if (res.code === 200) {
      Toast.hide();
      this.setState({
        data: res.data,
      });
    } else {
      Toast.offline('网络异常', 2, f => f, false);
    }
  }

  showActionSheet = () => {
    const { data } = this.state;
    if (data.length === 0) {
      Toast.info('您还没有收藏', 2, f => f, false);
      return false;
    }

    alert('', <Text style={{ fontSize: 20, lineHeight: 60, textAlign: 'center' }}>确定清除所有收藏？</Text>, [
      { text: '取消', onPress: f => f },
      {
        text: '确定', onPress: async () => {
        AsyncStorage.clear(() => {
          this.setState({ data: [] });
          Toast.info('清除成功', 2, f => f, false);
        });
      }
      },
    ]);
  };

  renderPureText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  renderOnePicText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        extra={<Image source={{ uri: item.images[0] }} style={styles.cover} />}
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  renderThreePicText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listImages}>
          <Image source={{ uri: item.images[0] }} style={styles.listImageCell} />
          <View style={{ width: 5 }}></View>
          <Image source={{ uri: item.images[1] }} style={styles.listImageCell} />
          <View style={{ width: 5 }}></View>
          <Image source={{ uri: item.images[2] }} style={styles.listImageCell} />
        </View>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  render() {
    const { data } = this.state;
    return (
      <ScrollView>
        <StatusBar barStyle="light-content" />
        {
          data.length === 0
            ?
            <WingBlank size="sm">
              <Text style={styles.font}>暂无收藏.</Text>
              </WingBlank>
            :
            <List style={styles.list}>
              {
                Array.isArray(data) && data.map(item => {
                  if (item.images.length === 0) {
                    return this.renderPureText(item)
                  } else if (item.images.length > 0 && item.images.length < 3) {
                    return this.renderOnePicText(item)
                  } else if (item.images.length >= 3) {
                    return this.renderThreePicText(item)
                  }
                })
              }
            </List>
        }
      </ScrollView>
    );
  }
}
